﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace DllShepherd.Core
{
    public class HttpUtils
    {
        public static string PostRequest(string url, List<KeyValuePair<string, string>> paramters)
        {
            return PostRequest(url, paramters, null);
        }

        /// <summary>
        /// HTTP Post
        /// (Based on code from: http://www.hanselman.com/blog/HTTPPOSTsAndHTTPGETsWithWebClientAndCAndFakingAPostBack.aspx)
        /// </summary>
        /// <param name="url"></param>
        /// <param name="paramters"></param>
        /// <param name="referer"></param>
        /// <returns></returns>
        public static string PostRequest(string url, List<KeyValuePair<string, string>> paramters, string referer)
        {
            var req = WebRequest.Create(url);
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "POST";

            var parameters = GetParameters(paramters);

            //We need to count how many bytes we're sending. 
            var bytes = Encoding.ASCII.GetBytes(parameters);
            req.ContentLength = bytes.Length;

            ((HttpWebRequest)req).CookieContainer = new CookieContainer();
            if (!String.IsNullOrEmpty(referer))
                ((HttpWebRequest)req).Referer = referer;

            var os = req.GetRequestStream();
            os.Write(bytes, 0, bytes.Length); //Push it out there
            os.Close();
            var resp = req.GetResponse();
            if (resp == null)
                return null;
            var sr = new StreamReader(resp.GetResponseStream());
            return sr.ReadToEnd().Trim();
        }

        private static string GetParameters(IEnumerable<KeyValuePair<string, string>> paramters)
        {
            var parameters = new StringBuilder();
            foreach (var pair in paramters)
            {
                parameters.Append(pair.Key + "=" + pair.Value + "&");
            }
            var result = parameters.ToString();
            return result.Substring(0, result.Length - 1);
        }
    }
}
